import * as path from 'path';
import { Context } from 'egg';

const isExclude = (url: string, exclude: string | RegExp) => {
  if (typeof url === 'string') {
    exclude = new RegExp(exclude);
  }
  return (exclude as RegExp).test(url);
};

export default (options: any = {}) => {
  return async (ctx: Context, next) => {
    const url = ctx.request.url;
    
    const extname = path.extname(url);
    console.log('url', url);
    if (extname) return await next();
    let excludes: Array<RegExp | string> = options.exclude || [];
    if (!Array.isArray(excludes)) {
      excludes = [excludes];
    }
    for (let i = 0; i < excludes.length; i++) {
      const exclude = excludes[i];
      if (isExclude(url, exclude)) {
        return await next();
      }
    }
    const user = ctx.session.user;
    if (!user) {
      console.log('没权限。。。');
      // return ctx.redirect('login');
      ctx.set('Location', './login');
      ctx.status = 302;
      return await ctx.render('login/index', {
        error: ''
      });
    }
    await next();
  };
};
